package com.jinmingwu.musicplay.myApplication;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.jinmingwu.musicplay.R;
import com.jinmingwu.musicplay.data.MusicList;

import java.io.IOException;
import java.util.Random;


/**
 * Created by jinmingwu on 2018/9/21.
 */

public class MusicService extends Service {

    //播放控制命令，标识操作
    public static final int COMMAND_UNKNOWN = -1;
    public static final int COMMAND_PLAY = 0;
    public static final int COMMAND_PAUSE = 1;
    public static final int COMMAND_STOP = 2;
    public static final int COMMAND_RESUME = 3;
    public static final int COMMAND_PREVIOUS = 4;
    public static final int COMMAND_NEXT = 5;
    public static final int COMMAND_CHECK_IS_PLAYING = 6;
    public static final int COMMAND_SEEK_TO = 7;
    public static final int COMMAND_RANDOM = 8;
    public static final int COMMAND_LIST_CYCLE_UP = 9;
    public static final int COMMAND_LIST_CYCLE_DOWN = 10;

    //播放状态
    public static final int STATUS_PLAYING = 0;
    public static final int STATUS_PAUSED = 1;
    public static final int STATUS_STOPPED = 2;
    public static final int STATUS_COMPLETED = 3;

    //广播标识
    public static final String BROADCAST_MUSICSERVICE_CONTROL = "MusicService.ACTION_CONTROL";
    public static final String BROADCAST_MUSICSERVICE_UPDATE_STATUS = "MusicService.ACTION_UPDATE";

    //歌曲序号
    private int number = 0;
    private int status;

    //媒体播放类
    private MediaPlayer player = new MediaPlayer();

    //广播接收器
    private CommandReceiver receiver;

    //电话标识
    private boolean phone = false;

    @Override
    public void onCreate() {
        super.onCreate();

        //绑定广播接收器，接收广播
        bindCommandReceiver();
        status = MusicService.STATUS_STOPPED;

//        PermissionUtils.checkPhonePermission(this);
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public void onDestroy() {
        //释放播放器资源
        if (player != null) {
            player.release();
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    class MyPhoneListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    if (status == MusicService.STATUS_PLAYING) {
                        pause();
                        phone = true;
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if (phone == true) {
                        resume();
                        phone = false;
                    }
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }

    //绑定广播接收器
    private void bindCommandReceiver() {
        receiver = new CommandReceiver();
        IntentFilter filter = new IntentFilter(BROADCAST_MUSICSERVICE_CONTROL);
        registerReceiver(receiver, filter);
    }

    //发送广播，提醒状态改变了
    private void sendBroadcastOnStatusChanged(int status) {
        Intent intent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        intent.putExtra("status", status);
        if (status != STATUS_STOPPED) {
            intent.putExtra("time", player.getCurrentPosition());
            intent.putExtra("duration", player.getDuration());
            intent.putExtra("number", number);
        }
        sendBroadcast(intent);
    }

    //内部类，接收广播命令，并执行操作
    class CommandReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //获取命令
            int command = intent.getIntExtra("command", COMMAND_UNKNOWN);
            //执行命令
            switch (command) {
                case COMMAND_PLAY:
                    number = intent.getIntExtra("number", 0);
                    play(number);
                    break;
                case COMMAND_PREVIOUS:
                    moveNumberToPrevious(COMMAND_PREVIOUS);
                    break;
                case COMMAND_NEXT:
                    moveNumberToNext(COMMAND_NEXT);
                    break;
                case COMMAND_PAUSE:
                    pause();
                    break;
                case COMMAND_STOP:
                    stop();
                    break;
                case COMMAND_RESUME:
                    resume();
                    break;
                case COMMAND_CHECK_IS_PLAYING:
                    if (player != null && player.isPlaying()) {
                        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
                    }
                    break;
                case COMMAND_SEEK_TO:
                    seekTo(intent.getIntExtra("time", 0));
                    break;
                case COMMAND_RANDOM:
                    // 随机播放
                    number = randomPlay();
                    play(number);
                    break;
                case COMMAND_LIST_CYCLE_UP:
                    //循环列表下的上一曲
                    moveNumberToPrevious(COMMAND_LIST_CYCLE_UP);
                    break;
                case COMMAND_LIST_CYCLE_DOWN:
                    //循环列表下的下一曲
                    moveNumberToNext(COMMAND_LIST_CYCLE_DOWN);
                    break;
                case COMMAND_UNKNOWN:
                default:
                    break;
            }

        }
    }

    //播放结束监听器
    MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer player) {
            if (player.isLooping()) {
                replay();
            } else {
                sendBroadcastOnStatusChanged(MusicService.STATUS_COMPLETED);
            }
        }
    };

    //读取音乐文件
    private void load(int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getPath());
            player.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //注册监听器
        player.setOnCompletionListener(completionListener);
    }

    //播放音乐
    private void play(int number) {
        //停止当前播放
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        player.start();
        //设置播放状态
        status = MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }

    //暂停音乐
    private void pause() {
        if (player.isPlaying()) {
            player.pause();
            status = MusicService.STATUS_PAUSED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_PAUSED);
        }
    }

    //停止播放
    private void stop() {
        if (status != MusicService.STATUS_STOPPED) {
            player.stop();
            status = MusicService.STATUS_STOPPED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_STOPPED);
        }
    }

    //恢复播放 暂停之后恢复
    private void resume() {
        player.start();
        status = MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }

    //重新播放 播放完毕之后
    private void replay() {
        player.start();
        status = MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }

    //下一曲
    private void moveNumberToNext(int num) {
        if (number == (MusicList.getMusicList().size() - 1)) {
            switch (num) {
                case COMMAND_LIST_CYCLE_DOWN:
                    number = 0;
                    play(number);
                    break;
                default:
                    Toast.makeText(MusicService.this, R.string.tip_reach_bottom, Toast.LENGTH_SHORT).show();
                    break;
            }
        } else {
            ++number;
            play(number);
        }
    }

    //上一曲
    private void moveNumberToPrevious(int num) {
        if (number == 0) {
            switch (num) {
                case COMMAND_LIST_CYCLE_UP:
                    number = MusicList.getMusicList().size() - 1;
                    play(number);
                    break;
                default:
                    Toast.makeText(this, R.string.tip_reach_top, Toast.LENGTH_SHORT).show();
                    break;
            }
        } else {
            --number;
            play(number);
        }
    }

    private void seekTo(int time) {
        player.seekTo(time);
    }

    //随机播放
    private int randomPlay() {
        Random random = new Random();
        int length = MusicList.getMusicList().size();
        int num;
        do {
            num = random.nextInt(length);
        } while (num == number);
        return num;
    }
}
